package com.xibei.homepage.service.impl;

import com.xibei.homepage.CourseInfo;
import com.xibei.homepage.CourseInfosRequest;
import com.xibei.homepage.dao.HomepageCourseDao;
import com.xibei.homepage.entity.HomepageCourse;
import com.xibei.homepage.service.ICourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CourseServiceImpl implements ICourseService {

    @Autowired
    private HomepageCourseDao homepageCourseDao;


    /***
     * 返回无效对象在 Entity中定义;
     * @param id
     * @return
     */
    @Override
    public CourseInfo getCourseInfo(Long id) {
        Optional<HomepageCourse> course = homepageCourseDao.findById(id);
        /**如果为空，返回无效*/
        return buildCourseInfo(course.orElse(HomepageCourse.invalid()));
    }

    /**
     * 根据请求ids获取信息集合，如果为空，则返回空集
     * @param request
     * @return
     */
    @Override
    public List<CourseInfo> getCourseInfos(CourseInfosRequest request) {

        if(CollectionUtils.isEmpty(request.getIds()))
        {
            return Collections.emptyList();
        }
        List<HomepageCourse> homepageCourses = homepageCourseDao.findAllById(request.getIds());
        return homepageCourses.stream()
                .map(this::buildCourseInfo)
                .collect(Collectors.toList());
    }

    private CourseInfo buildCourseInfo(HomepageCourse course){
        return CourseInfo.builder()
                .id(course.getId())
                .courseName(course.getCourseName())
                .courseType(course.getCourseType()==0?"免费课程":"实战课程")
                .courseIcon(course.getCourseIntro())
                .courseIntro(course.getCourseIntro())
        .build();
    }
}
